package research.sbookmarking.input.xml;

import java.util.*;
import org.afox.parsers.xml.*;
import org.afox.util.*;
import org.xml.sax.*;
import javax.management.modelmbean.XMLParseException;

/**
 *  This class tells reflectiveHandler how to process the tags in an xml file.
 *  <p>
 *  The tags that this class processes are: <Setting>, <Command>, <Param>, <List> and <CParam>.
 *  <p> 
 *  @author <A HREF="mailto:aatleung@gmail.com">Albert Leung</a>
 *  @version 1.0
 *
 */
public class SettingHandler extends ReflectiveHandler {
	private String currentClass;
	private String classPath;
	private HashMap parameters = new HashMap();
	private ArrayList commands = new ArrayList();
	private ArrayList query = new ArrayList();

	public void startSetting(Attributes attrs)	{
		getMainHandler().setResult(commands);
	}

	public void startCommand(Attributes attrs){
		classPath = attrs.getValue("classpath");
		currentClass = attrs.getValue("class");
		parameters.clear();
	}

	public void endCommand() {
		commands.add(create());
	}

	public void startParam(Attributes attrs) {
		parameters.put(attrs.getValue("name"),StringType.parse(attrs.getValue("value")));
	}
	
	public void startCParam(Attributes attrs) {
		query.add(StringType.parse(attrs.getValue("value")));
	}

	public void startList(Attributes attrs) {
		query.clear();
	}

	public void endList() {
		parameters.put("list", query.clone());
	}
	
	private Object create () {
		ArrayList param = new ArrayList();

		try {
			/*
			if (parameters.get("container")== null) {
				throw (new XMLParseException ("Could not find the container name to be used.")); 
			}
			*/
			if (parameters.get("queryName")==null){
				throw (new XMLParseException ("Could not find the name of the command to be executed.")); 
			}
			else if (parameters.get("list")==null) {
				throw (new XMLParseException ("Could not find the list to be queryed against Connotea.org.")); 
			}
			param.add(parameters.get("queryName"));
			param.add(parameters.get("list"));
			
			if (parameters.get("limit")!=null) {
				param.add(parameters.get("limit"));

				if (parameters.get("start")!=null) {
					param.add(parameters.get("start"));
				}
			}

			if (parameters.get("users")!=null) {
				param.add(parameters.get("users"));
			}
			return (RFactory.newInstance(classPath+currentClass, param));			
		}
		catch(Exception x){
			System.out.println("Error instantiating Command: " + classPath + currentClass +
			"(" + param + "): ");
			x.printStackTrace();
		}
		
		return null;
	}
}
